package com.ctyon.watchmanager.viewmodel;

import android.app.Application;

import com.alibaba.fastjson.JSON;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.SPUtils;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.model.net.entity.Watch;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MediatorLiveData;
import io.reactivex.schedulers.Schedulers;

import static com.ctyon.common.util.SPUtils.WATCH_ID;

/**
 * CreateDate：19-1-3 on 下午3:41
 * Describe:
 * Coder: lee
 */
public class HomeViewModel extends AndroidViewModel {

    private final MediatorLiveData<List<Integer>> mObservableBanner;
    private final MediatorLiveData<Watch> mObservableWatch;
    private List<Integer> mBanner;
    private Watch watch;

    public HomeViewModel(@NonNull Application application) {
        super(application);

        mBanner = new ArrayList<>();
        watch = new Watch();

        mObservableBanner = new MediatorLiveData<>();
        mObservableWatch = new MediatorLiveData<>();

        mObservableBanner.setValue(mBanner);
        mObservableWatch.setValue(watch);

    }

    public MediatorLiveData<List<Integer>> getBanner() {
        Logger.d("getBanner");
        return mObservableBanner;
    }

    public MediatorLiveData<Watch> getWatch() {
        Logger.d("getWatch");
        return mObservableWatch;
    }

    public void initWatch() {
        Logger.d("initWatch");
        try {
            NetService.getInstance()
                    .getWatchList(BasicApp.getInstance().getManager().getManagerId())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new BaseObserver<BaseResponseEntity>() {
                        @Override
                        public void onSuccess(BaseResponseEntity responseEntity) {
                            Logger.d("onSuccess : " + responseEntity.toString());
                            Watch mWatch = null;
                            if (null != responseEntity.data) {
                                String data = responseEntity.data.toString();
                                Logger.d("data : " + data);
                                if (data.contains("=")) {
                                    data = data.replace("=", ":");
                                }
                                if (data.contains(":,")) {
                                    data = data.replace(":,", ":null,");
                                }
                                if (data.contains(":}")) {
                                    data = data.replace(":}", ":null}");
                                }
                                Logger.d("data : " + data);

                                List<Watch> watchList = new ArrayList<>();
                                try {
                                    JSONArray jsonArray = new JSONArray(data);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject obj = jsonArray.getJSONObject(i);
                                        Logger.d("obj : " + obj.toString());
                                        Watch watch = JSON.parseObject(obj.toString(), Watch.class);
                                        String meid = watch.getMeid();
                                        StringBuilder sb = new StringBuilder();
                                        for (int j = 0; j < 10 - meid.length(); j++) {
                                            sb.append("0");
                                        }
                                        sb.append(meid);
                                        watch.setMeid(sb.toString());
                                        watchList.add(watch);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                if ((watchList != null && watchList.size() > 0)) {
                                    String watchId = SPUtils.getInstance().getString(WATCH_ID);
                                    if (!DataUtil.isEmptyOr(watchId)) {
                                        for (Watch watch : watchList) {
                                            if (watchId.equals(watch.getMeid())) {
                                                mWatch = watch;
                                            }
                                        }
                                    }
                                    if (null == mWatch){
                                        mWatch = watchList.get(0);
                                        SPUtils.getInstance().put(WATCH_ID, mWatch.getMeid());
                                    }
                                }
                                BasicApp.getInstance().setWatch(mWatch);
                            }
                            Logger.d("initWatch : " + mWatch);
                            mObservableWatch.postValue(mWatch);
                        }
                    });
        }catch (Exception e){
            Logger.d("initWatchError : " + e);
        }

    }

    public void initBanner(){
        Logger.d("initBanner");
        BasicApp.getInstance().getAppExecutors().networkIO().execute(() -> {
            Integer[] banners = {
                    R.mipmap.banner1,
                    R.mipmap.banner2,
                    R.mipmap.banner3,
                    R.mipmap.banner4,
                    R.mipmap.banner5
            };
            mBanner.addAll(Arrays.asList(banners));

        });

    }

}
